import express from "express";
import { Schema } from "mongoose";
import { baseResp, bottleModalname, bottleSchematype } from "../common";
import { addData, findAll, updateData, deleteData } from "../mdb/controlDB";

const router = express.Router();
const bottleschema = new Schema(bottleSchematype);

type TBottle = {
  name: string;
  height: number;
  diameter: number;
  depth: number;
  volume: number;
  shape: string;
  id?: string;
  _id?: string;
  __v?: number;
};

// 新增数据
router.post("/add", function (req, res) {
  const param = req.body;
  const addback = (data: any) => {
    if (data.success === false) {
      res.json(Object.assign({}, baseResp, data));
    } else {
      res.json(Object.assign({}, baseResp));
    }
  };

  addData({
    schematype: bottleschema,
    callback: addback,
    modalname: bottleModalname,
    param,
  });
});

// 获取所有试剂瓶子
router.get("/all", function (req, res) {
  const param = req.body;
  const findback = (data: TBottle[]) => {
    let temp: TBottle[] = [];
    if (data && data.length) {
      data.forEach((item: TBottle) => {
        const { name, height, diameter, depth, volume, shape, _id } = item;
        temp.push({
          name,
          height,
          diameter,
          depth,
          volume,
          shape,
          id: _id,
        });
      });
    }
    res.json(Object.assign({}, baseResp, { data: temp }));
  };

  findAll({
    schematype: bottleschema,
    callback: findback,
    modalname: bottleModalname,
    param,
  });
});

// 编辑试剂
router.post("/update", (req, res) => {
  const param = req.body;
  const editback = (data: any) => {
    res.json(Object.assign({}, baseResp, { data }));
  };
  updateData({
    schematype: bottleschema,
    callback: editback,
    modalname: bottleModalname,
    param,
  });
});

// 删除试剂
router.post("/del", (req, res) => {
  const param = req.body;
  const delback = (data: any) => {
    res.json(Object.assign({}, baseResp, data));
  };
  deleteData({
    schematype: bottleschema,
    callback: delback,
    modalname: bottleModalname,
    param,
  });
});

export default router;
